# -*- coding: utf-8 -*-

import string
import re
import random
import glob
import sys
import os

import pepe.glib as g
import pepe.p_txt.bigtxt as bt
import pepe.p_filesystem.basic as pfb

class lines:
    ''' read big text file as iterator
    '''
    def __init__(self , flpath_s):
        self.flpath_s = flpath_s
        self.sfile_fl = open(flpath_s, 'rb') 
    def __getitem__( self , index ):
        line_s = self.sfile_fl.readline()
        if line_s:
            return line_s
        else:
            raise IndexError

def main(filemask):
    
    '''     Edits text file to hide personal data.
     Keeps words from file 'garbler_words' unchanged.
     Numeric and nonalphabetic characters remain unchanged.

        Syntax:     garbler <input file mask>
        Example:    garbler *.txt
    '''
    
    try:
        li=[]
        for line1 in lines('garbler_words'):
            line1 = re.sub('\x0D\x0A', '', line1)
            line1 = re.sub('\x0D', '', line1)
            line1 = re.sub('\x0A', '', line1)
            for word1 in line1.split(" "):
                li.append(string.upper(word1))
    except IOError:
        print """
        Running without file 'garbler_words'.
        Words (if placed) in this file will be excluded from garbler processing.
        """
        
    for f in glob.glob(filemask):
        print '\t', g.timenow(), f
        of=open('garbler_' + f, 'wb')
        for line in lines(f):
            for word in line.split(" "):

                if not string.upper(word) in li:
                    for letter in word:
                        if re.search('[A-ZÁÉĚÍÝÓÚŮČĎŇŘŠŤŽ]',letter):
                            of.write(chr(random.randint(65,90)))
                        elif re.search('[a-záéěíýóúůčďňřšťž]',letter):
                            of.write(chr(random.randint(97,122)))
                        else: of.write(str(letter))
                    if word == '': 
                        of.write(' ')
                    elif letter <> '\n':
                        of.write(' ')
                elif string.upper(word) in li:
                    of.write(word+' ')
                else:
                    pass
        of.close()
        print '\t', g.timenow()
    
if __name__ == "__main__":
    """"""
    #print sys.argv
    print main.__doc__
    if len(sys.argv) == 2:
        main(filemask=sys.argv[1])
    else:
        print '''
        Error in syntax!
        Syntax example: garbler <file(s)-mask-name>
        '''
